package com.iris.live.services.report.sources;


import com.iris.live.services.common.DateFormatUtils;
import com.iris.live.services.data.repositories.Lsh经销商表Repository;
import com.iris.live.services.data.repositories.ReportRepository;
import com.iris.live.services.data.repositories.SetRepository;
import com.iris.live.services.report.Cell;
import com.iris.live.services.report.IExcelReportSource;
import com.iris.live.services.report.Row;
import com.iris.live.services.report.Sheet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by liuhang on 2017/4/24.
 */
@Component("ExportFlowLogSource")
public class ExportFlowLogSource implements IExcelReportSource {
    private static final String [] titles = {"序号", "前台", "是否首次", "到店时间", "离店时间", "停留时间", "试驾开始", "试驾结束", "试驾时长",
            "试驾车型", "是否预约", "是否指定SC", "指定SC", "接待SC", "顾客姓名", "联系电话",
            "意向车型", "现有品牌", "客户级别", "首次来源渠道" ,"渠道细分备注", "再次来源渠道", "是否报价", "是否订单", "是否交车", "到店目的", "其他目的备注"};

    private static final String [] titlesAll = {"序号", "前台", "是否首次", "到店时间", "离店时间", "停留时间", "试驾开始", "试驾结束", "试驾时长",
            "试驾车型", "是否预约", "是否指定SC", "指定SC", "接待SC", "顾客姓名", "联系电话",
            "意向车型", "现有品牌", "客户级别", "首次来源渠道" ,"渠道细分备注", "再次来源渠道", "是否报价", "是否订单", "是否交车", "到店目的", "其他目的备注", "日期"};
    private static Logger logger = LoggerFactory.getLogger(ExportFlowLogSource.class);
    @Autowired
    private ReportRepository repository;

    @Autowired
    private SetRepository setRepository;

    @Autowired
    private Lsh经销商表Repository lsh经销商表Repository;

    @Override
    public Sheet[] getSheets(Map<String, Object> context) {
        String startTime = context.get("startTime").toString();
        String endTime = context.get("endTime").toString();
        List<String> timeList = new ArrayList<>();
        try {
            timeList = DateFormatUtils.splitDate(startTime,endTime);
        } catch (ParseException e) {
            logger.error("获取sheet个数出错");
        }
        Integer isPage = Integer.parseInt(context.get("isPage").toString());
        if(isPage==1) {
            Sheet[] sheets = new Sheet[timeList.size()];
            for(int i=0;i<timeList.size();i++) {
                sheets[i] = new Sheet(""+timeList.get(i), "--"+timeList.get(i), true);
            }
            return sheets;
        }
        else{
            Sheet[] sheets = new Sheet[1];
            sheets[0] = new Sheet(""+startTime+"--"+endTime, ""+startTime+"--"+endTime, true);
            return sheets;
        }

    }

    @Override
    public List<Row> getSheetRows(Map<String, Object> context, Sheet sheet) {
        String dealer = (String) context.get("dealer");
        String startTime = context.get("startTime").toString();
        String endTime =  context.get("endTime").toString();
        Integer isClue = Integer.parseInt(context.get("isClue").toString());
        Integer isPage = Integer.parseInt(context.get("isPage").toString());
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        if(isPage==1) {
            try {
                Date start = DateFormatUtils.parseStrToSqlDate(startTime);
                Date end = DateFormatUtils.parseStrToSqlDate(endTime);
                if (start.getTime() > end.getTime()) {
                    return null;
                }
                startTime = end.toString();
                endTime = end.toString();
                context.put("endTime", DateFormatUtils.subStringToDate(endTime.toString(), 1));
            } catch (ParseException e) {
                return null;
            }
        }

        int index;
        List<Row> rows = new ArrayList<>();
        Map<String, Object> m=repository.getClueInfo(  dealer);
        String dealerName=lsh经销商表Repository.findNameByPermit(dealer);
        Cell[] c = {new Cell(dealerName, 3 ),new Cell(sdf.format(new java.util.Date()), 5 )};
        Cell[] d = {new Cell(dealer, 3 ),
                new Cell(m.get("callin"), 13 ),new Cell(m.get("network"), 14 ),new Cell(m.get("initiative"), 15),new Cell(m.get("recommend"), 16 )
                ,new Cell(m.get("buyAgain"), 17 ),new Cell(m.get("active"), 19 ),new Cell(m.get("sleep"), 20 )};
        Cell[] a = {new Cell(dealer, 3 )};
        for(index = 0; index < 6; index++) {
            if(index == 1){
                rows.add(new Row(c));
            } else if(index == 2){
                if(isClue==1){
                    rows.add(new Row(d));
                }
                    else{
                    rows.add(new Row(a));
                }
            }
                else {
                rows.add(new Row());
            }
        }

        if(isPage==1){//若是1  则分页
        rows.add(new Row(getTitleCells(titles)));
        }
        else{
            rows.add(new Row(getTitleCells(titlesAll)));
        }
        //数据输出
        index = 0;
        List<Map<String,Object>> list;
        List<Map<String,Object>> listLast;
          list = repository.getDisplayFlowInfo(dealer, startTime, endTime);
        if(list != null) {
                for (Object o : list) {
                    Map map = (Map) o;
                    if(isPage==1){ //若是1 则分页
                    rows.add(new Row(getDataCells(index++, titles, o)));}
                    else{
                        rows.add(new Row(getDataCells(index++, titlesAll, o)));
                    }
            }
        }

        return rows;
    }

    /**
     * 获取Excel 标题行
     * @param titles
     * @return
     */
    private  Cell[] getTitleCells(String[] titles){
        Cell[] cells = new Cell[titles.length];
        for(int index = 0; index < titles.length; index++){
            cells[index] = new Cell(titles[index], index );
        }

        return cells;
    }

    /**
     * 获取数据行
     * @param rowIndex
     * @param columns
     * @param o
     * @return
     */
    private Cell[] getDataCells(int rowIndex, String[] columns, Object o) {
        Map map = (Map) o;
        Cell[] cells = new Cell[columns.length];
        cells[0] = new Cell(rowIndex+1 + "", 0);
        for(int index = 1; index < columns.length; index++){
            String name = columns[index];
            if (index == 5) {
                cells[index] = new Cell(map.get(name) == null ? "" : map.get(columns[index]).toString() + "分", index );
            } else {
                cells[index] = new Cell(map.get(name) == null ? "" : map.get(columns[index]).toString(), index);
            }
        }

        return cells;
    }
}